package com.campus.help.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.campus.help.config.WechatConfig;
import com.campus.help.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信API工具类
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
@Component
public class WechatUtils {

    @Autowired
    private WechatConfig wechatConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过code获取微信用户session信息
     *
     * @param code 微信登录凭证
     * @return 微信用户session信息
     */
    public WechatSessionInfo code2Session(String code)
    {
        try {
            String url = wechatConfig.getApiBaseUrl() + wechatConfig.getCode2SessionUrl();
            
            Map<String, String> params = new HashMap<>();
            params.put("appid", wechatConfig.getAppId());
            params.put("secret", wechatConfig.getAppSecret());
            params.put("js_code", code);
            params.put("grant_type", "authorization_code");

            String response = restTemplate.getForObject(url + "?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}", 
                String.class, params);

            log.info("微信code2Session响应: {}", response);

            JSONObject jsonResponse = JSON.parseObject(response);
            
            if (jsonResponse.containsKey("errcode")) {
                int errcode = jsonResponse.getIntValue("errcode");
                String errmsg = jsonResponse.getString("errmsg");
                log.error("微信code2Session失败: errcode={}, errmsg={}", errcode, errmsg);
                throw new BusinessException("微信登录失败: " + errmsg);
            }

            WechatSessionInfo sessionInfo = new WechatSessionInfo();
            sessionInfo.setOpenid(jsonResponse.getString("openid"));
            sessionInfo.setSessionKey(jsonResponse.getString("session_key"));
            sessionInfo.setUnionid(jsonResponse.getString("unionid"));

            return sessionInfo;
        } catch (Exception e) {
            log.error("调用微信code2Session接口异常", e);
            throw new BusinessException("微信登录失败");
        }
    }

    /**
     * 解密微信用户信息
     *
     * @param encryptedData 加密数据
     * @param sessionKey 会话密钥
     * @param iv 初始向量
     * @return 解密后的用户信息
     */
    public WechatUserInfo decryptUserInfo(String encryptedData, String sessionKey, String iv) {
        try {
            String decryptedData = WechatAESUtils.decrypt(encryptedData, sessionKey, iv);
            JSONObject userInfoJson = JSON.parseObject(decryptedData);
            
            WechatUserInfo userInfo = new WechatUserInfo();
            userInfo.setOpenid(userInfoJson.getString("openId"));
            userInfo.setUnionid(userInfoJson.getString("unionId"));
            userInfo.setNickname(userInfoJson.getString("nickName"));
            userInfo.setAvatarUrl(userInfoJson.getString("avatarUrl"));
            userInfo.setGender(userInfoJson.getIntValue("gender"));
            userInfo.setCity(userInfoJson.getString("city"));
            userInfo.setProvince(userInfoJson.getString("province"));
            userInfo.setCountry(userInfoJson.getString("country"));
            userInfo.setLanguage(userInfoJson.getString("language"));

            return userInfo;
        } catch (Exception e) {
            log.error("解密微信用户信息失败", e);
            throw new BusinessException("获取用户信息失败");
        }
    }

    /**
     * 微信Session信息
     */
    public static class WechatSessionInfo {
        private String openid;
        private String sessionKey;
        private String unionid;

        // getter和setter方法
        public String getOpenid() { return openid; }
        public void setOpenid(String openid) { this.openid = openid; }
        public String getSessionKey() { return sessionKey; }
        public void setSessionKey(String sessionKey) { this.sessionKey = sessionKey; }
        public String getUnionid() { return unionid; }
        public void setUnionid(String unionid) { this.unionid = unionid; }
    }

    /**
     * 微信用户信息
     */
    public static class WechatUserInfo {
        private String openid;
        private String unionid;
        private String nickname;
        private String avatarUrl;
        private Integer gender;
        private String city;
        private String province;
        private String country;
        private String language;

        // getter和setter方法
        public String getOpenid() { return openid; }
        public void setOpenid(String openid) { this.openid = openid; }
        public String getUnionid() { return unionid; }
        public void setUnionid(String unionid) { this.unionid = unionid; }
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getAvatarUrl() { return avatarUrl; }
        public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; }
        public Integer getGender() { return gender; }
        public void setGender(Integer gender) { this.gender = gender; }
        public String getCity() { return city; }
        public void setCity(String city) { this.city = city; }
        public String getProvince() { return province; }
        public void setProvince(String province) { this.province = province; }
        public String getCountry() { return country; }
        public void setCountry(String country) { this.country = country; }
        public String getLanguage() { return language; }
        public void setLanguage(String language) { this.language = language; }
    }
}
